﻿using Beauty.Net.MiniExcel.Core;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Net.Mime;
using Microsoft.Extensions.Logging;

namespace Beauty.NetWebApi.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class ExcelController : ControllerBase
    {
        private readonly IMiniExcelService _miniExcelService;
        private readonly ILogger<ExcelController> _logger;
        
        public ExcelController(IMiniExcelService miniExcelService, ILogger<ExcelController> logger)
        {
            _miniExcelService = miniExcelService;
            _logger = logger;
        }

        [HttpGet("export")]
        public IActionResult ExportUsers()
        {
            try
            {
                // 获取用户数据
                var users = this.GetSampleData();

                // 导出到内存流
                using var stream = _miniExcelService.ExportToStream(users, "用户列表");

                // 返回文件
                return File(stream, MediaTypeNames.Application.Octet, "users.xlsx");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "导出用户数据失败");
                return BadRequest(new { Message = "导出失败", Error = ex.Message });
            }
        }

        [HttpPost("import")]
        public async Task<IActionResult> ImportUsers(IFormFile file)
        {
            try
            {
                if (file == null || file.Length == 0)
                    return BadRequest(new { Message = "请选择要上传的文件" });

                // 验证文件类型
                var fileExtension = Path.GetExtension(file.FileName).ToLowerInvariant();
                if (fileExtension != ".xlsx" && fileExtension != ".xls")
                    return BadRequest(new { Message = "仅支持.xlsx和.xls格式的Excel文件" });

                // 使用文件流直接导入
                using var stream = file.OpenReadStream();
                var users = _miniExcelService.ImportFromStream<UserData>(stream);

                return Ok(new { 
                    Message = "导入成功",
                    ImportedCount = users.Count,
                    Data = users.Take(10) // 只返回前10条数据
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "导入用户数据失败");
                return BadRequest(new { Message = "导入失败", Error = ex.Message });
            }
        }

        /// <summary>
        /// 获取示例数据
        /// </summary>
        /// <returns></returns>
        private List<UserData> GetSampleData()
        {
            return new List<UserData>
            {
                new UserData { Id = 1, Name = "张三", Age = 28, Email = "zhangsan@example.com", RegisterDate = new DateTime(2023, 1, 15) },
                new UserData { Id = 2, Name = "李四", Age = 32, Email = "lisi@example.com", RegisterDate = new DateTime(2023, 2, 10) },
                new UserData { Id = 3, Name = "王五", Age = 45, Email = "wangwu@example.com", RegisterDate = new DateTime(2023, 3, 5) }
            };
        }
    }

    /// <summary>
    /// 用户数据模型
    /// </summary>
    public class UserData
    {
        /// <summary>
        /// 用户ID
        /// </summary>
        public int Id { get; set; }
        
        /// <summary>
        /// 用户名
        /// </summary>
        public string Name { get; set; }
        
        /// <summary>
        /// 年龄
        /// </summary>
        public int Age { get; set; }
        
        /// <summary>
        /// 邮箱
        /// </summary>
        public string Email { get; set; }
        
        /// <summary>
        /// 注册日期
        /// </summary>
        public DateTime RegisterDate { get; set; }
    }
}
